package cn.dakaqi.utils.http;


import cn.dakaqi.utils.rsa.RSAUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.util.HashMap;
import java.util.Map;

/**
 * HTTP请求类
 */
public class HttpInvoker
{
    private static Logger log = LoggerFactory.getLogger(HttpInvoker.class);
    private static final String METHOD_POST = "POST";
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String APPLICATION_JSON = "application/json;charset=" + DEFAULT_CHARSET;
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

    /**
     * GET请求
     *
     * @param url
     * @return 提取HTTP响应报文包体，以字符串形式返回
     * @throws java.io.IOException
     */
    public static String httpGet(String url)
    {
        log.info(url);
        String result = "";
        try
        {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            String ctype = "application/json;charset=" + DEFAULT_CHARSET;
            conn.setRequestProperty("Content-Type", ctype);

            // 获取URLConnection对象对应的输出流
            //BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            StringBuilder sbStr = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                sbStr.append(line);
            }
            bufferedReader.close();
            result = new String(sbStr.toString().getBytes());
        } catch (Exception e)
        {
            System.out.println("发送 GET 请求出现异常！" + e);
            e.printStackTrace();
        }
        System.out.println("http POST result---->" + result);
        return result;
    }

    /**
     * POST请求
     *
     * @param postUrl
     * @param postHeaders
     * @param postEntity
     * @return 提取HTTP响应报文包体，以字符串形式返回
     * @throws java.io.IOException
     */
    public static String httpPost(String postUrl, Map<String, String> postHeaders, String postEntity) throws IOException
    {

        URL postURL = new URL(postUrl.replace("?", ""));
        HttpURLConnection httpURLConnection = (HttpURLConnection) postURL.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setInstanceFollowRedirects(true);
        String ctype = "application/json;charset=" + DEFAULT_CHARSET;
        httpURLConnection.setRequestProperty("Content-Type", ctype);
        if (postHeaders != null)
        {
            for (String pKey : postHeaders.keySet())
            {

                httpURLConnection.setRequestProperty(pKey, postHeaders.get(pKey));
            }
        }
        if (postEntity != null)
        {
            DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
            out.writeBytes(postEntity);
            out.flush();
            out.close(); // flush and close
        }
        //connection.connect();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        StringBuilder sbStr = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null)
        {
            sbStr.append(line);

        }
        bufferedReader.close();
        httpURLConnection.disconnect();
        return new String(sbStr.toString().getBytes(), DEFAULT_CHARSET);
    }

    public static String httpPost1(String url, String param)
    {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try
        {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            String ctype = "application/json;charset=" + DEFAULT_CHARSET;
            conn.setRequestProperty("Content-Type", ctype);

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            //out = new PrintWriter(conn.getOutputStream());

            out = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_CHARSET);

            // 发送请求参数
            if (StringUtils.isNotEmpty(param))
                out.write(param);
            //out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            /*in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}*/

            //System.out.println("北航编码："+conn.getHeaderField("Content-Type"));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_CHARSET));
            StringBuilder sbStr = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                sbStr.append(line);
            }
            bufferedReader.close();
            result = sbStr.toString();
        } catch (Exception e)
        {
            System.out.println("param----------------->"+param);
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            } catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        System.out.println("http POST result---->" + result);
        return result;
    }

    public static String httpPostXML(String url, String param)
    {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try
        {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            String ctype = "text/xml;charset="+DEFAULT_CHARSET;
            conn.setRequestProperty("Content-Type", ctype);

            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            //out = new PrintWriter(conn.getOutputStream());

            out = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_CHARSET);
            // 发送请求参数
            if (StringUtils.isNotEmpty(param))
                out.write(param);
            //out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
			/*in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}*/

            //System.out.println("北航编码："+conn.getHeaderField("Content-Type"));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_CHARSET));
            StringBuilder sbStr = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null)
            {
                sbStr.append(line);
            }
            bufferedReader.close();
            result = sbStr.toString();

        } catch (Exception e)
        {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if (in != null)
                {
                    in.close();
                }
            } catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        return result;
    }



    public static String httpPostWithJSON(String url, String json) throws Exception
    {
        // 将JSON进行UTF-8编码,以便传输中文
        String encoderJson = URLEncoder.encode(json, DEFAULT_CHARSET);

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);

        StringEntity se = new StringEntity(encoderJson);
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
        httpPost.setEntity(se);
        HttpResponse result = httpClient.execute(httpPost);
        // 请求结束，返回结果
        String resData = EntityUtils.toString(result.getEntity());
        return resData;
    }

    public static String receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException
    {

        // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null)
        {
            sb.append(line);
        }

        // 将资料解码
        String reqBody = sb.toString();
        return URLDecoder.decode(reqBody, DEFAULT_CHARSET);
    }

    public static void main(String[] args)throws Exception
    {
        Map<String,String> map = new HashMap<String,String>();
        map.put("id","7");
        map.put("oldpassd","oldpassd");
        map.put("newpassd","newpassd");

        String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIwwlYLtylarTYcu1746MH3z0+OBo5wMDAs7fG5+2Pmb+Q99R+2Cjtkb60AWR8WrGa/9cuBaRIIhskNtD3oJ4J4rg2Q4jda6ytCcc4h0Dx8jZ2qhrwLwZaK4efG4bltxqFB28iQWMoDIbIia5wsFYdfqWd1ji75caCZKGxhH+BgFAgMBAAECgYEAhp+1RClEMJyKc/Ho3lWU8a8v4H9C9XygKD00zgtkI7fDojtF0nCY6ycjb8S1ob4gid/S7F3jAjCHtrZJsYFAwE1kcxisUP8plb/A1XUS3b+Pv3SUGtWAn/eQ5pxCWKkuDTyad9+DQIR9/Fug545/p4/DGdIXTOrNnN18Z27wSaECQQDwuIfvxrAI1t7e8HKw9Hhok1Nupdf5Dgf/kfZdJK+i1s8vnAnzHmBmyY4uPm+K2tlqIgfZZ7GChdUeWoM81nV9AkEAlRaGkLzcemsftkC/j16zTBZzaZwWRoOKqYsFsi2H+0qlr5WSh0sz75GGPZk00Q/+YItcnEpUyKBzSUU4wzMTKQJARhbUrcICO3Ckz/De1Bs6e+h5oHv1WHT3aziKrTAjW5yEEu6yDvHHS+Zf2aMgQyPZrgdelbSVgNWK6h2cnLgs2QJAEJhcTDoplJreAcx9Rjk1Xg/VsvjD5f94bNzjumylCUzK2pucnuC5HD6noa2vGmJcX2TD30XK4DYz/wDsi5Xg2QJAM7wpfbCbsARCgjUB5j+3LRoYUW9J29q42JvTXIMUaAsGJ/8n/mgniJCVFHd605ZrMu9umXhglyzaGZpeCZ6fqA==";
        String publickKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMMJWC7cpWq02HLte+OjB989PjgaOcDAwLO3xuftj5m/kPfUftgo7ZG+tAFkfFqxmv/XLgWkSCIbJDbQ96CeCeK4NkOI3WusrQnHOIdA8fI2dqoa8C8GWiuHnxuG5bcahQdvIkFjKAyGyImucLBWHX6lndY4u+XGgmShsYR/gYBQIDAQAB";

        String name= JSON.toJSONString(map);
        byte[] encodedData = RSAUtils.encryptByPublicKey(name.getBytes(), publickKey);

        encodedData = Base64.encodeBase64(encodedData, false, true);
        System.out.println(System.currentTimeMillis()+ "-2--加密后："+new String(encodedData, "UTF-8"));
        HttpInvoker.httpPost1("http://192.168.2.9:9080/unicorn/api/v1/account/modifypasswd3",new String(encodedData, "UTF-8"));
    }
}

